<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item>
              <el-button type="success" @click.stop="search">刷新</el-button>
              <el-button type="warning" @click.stop="edit">确定编辑</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-alert title="注：打钩表示左侧显示，并且点击确定编辑按钮保存编辑" type="warning" size="mini"></el-alert>
        <el-tree
          :data="menuList"
          node-key="id"
          ref="tree"
          highlight-current
          accordion
          :props="defaultProps"
          show-checkbox
          @check-change="handleCheckChange"
          :default-checked-keys="checkedKeys"
          style="margin-top:20px"
        >
        </el-tree>
      </el-card>
    </el-scrollbar>
  </div>
</template>
<script>
import { getMenuList, editMenu } from '@/network/api.js'

export default {
  name: 'menus',
  data() {
    return {
      searchForm: {},
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      checkedKeys: [], // 默认选中
      checkedList: [] // 选中
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    async search() {
      try {
        const rtn = await getMenuList(this.searchForm)
        this.menuList = rtn.menu_list
        // const checked = rtn.checked_list.replace(/(^,*)|(,*$)/g, '').split(',')
        // this.checkedKeys = checked[0] === '' ? [] : checked
        // this.checkedList = checked[0] === '' ? [] : checked
        this.checkedKeys = rtn.checked_list
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 菜单选中
    handleCheckChange(data, checked, indeterminate) {
      this.checkedList = [...this.$refs.tree.getHalfCheckedKeys(), this.$refs.tree.getCheckedKeys()]
    },
    // 编辑
    async edit() {
      if (this.checkedList.length === 0) {
        return this.$message.error('请重新打钩')
      }
      try {
        await editMenu({ left_menu_ids: this.checkedList })
        this.search()
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
